1.code
import React, { useState, useEffect } from 'react';
import styles from './ImageKeyboardControl.module.css';
import Image from 'next/image';
function ImageKeyboardControl() {
const containerWidth = 300;
const containerHeight = 300;
const imageSize = 50;
const [positionX, setPositionX] = useState(0);
const [positionY, setPositionY] = useState(0);
useEffect(() => {
const handleKeyPress = (event) => {
if (event.key === 'W' || event.key === 'w') {
setPositionY((prevY) => (prevY - 10 + containerHeight) % containerHeight);
} else if (event.key === 'S' || event.key === 's') {
setPositionY((prevY) => (prevY + 10) % containerHeight);
} else if (event.key === 'A' || event.key === 'a') {
setPositionX((prevX) => (prevX - 10 + containerWidth) % containerWidth);
} else if (event.key === 'D' || event.key === 'd') {
setPositionX((prevX) => (prevX + 10) % containerWidth);
}
};
window.addEventListener('keydown', handleKeyPress);
return () => {
window.removeEventListener('keydown', handleKeyPress);
};
}, []);
return (
<div className={styles.container}>
<div
className={`${styles.image}`}
style={{ left: `${positionX}px`, top: `${positionY}px` }}
>
<Image src="/void.png" width={imageSize} height={imageSize} alt="Image" />
</div>
</div>
);
}
export default ImageKeyboardControl;
.container {
position: relative;
width: 300px;
height: 300px;
overflow: hidden;
border: 1px solid #ccc;
}
.image {
position: absolute;
transition: left 0.1s, top 0.1s;
}
2.實作